import { WereWolfModule } from "@/werewolf/module";
import { WereWolfPlayer, WereWolfStatus } from "@/werewolf/player";
import { TeamScoreBoard } from "@sapi-game/gameComponent";
import { WereWolfMainState } from "../mainState/state";

export class WereWolfOutPhase extends WereWolfModule.State {
    outPlayer?: WereWolfPlayer | null;

    override onEnter(): void {
        this.outPlayer = this.getOutPlayer();
        if (this.outPlayer) {
            this.outPlayer.status = WereWolfStatus.justDead;
        }
        this.engine
            .getState(WereWolfMainState)
            ?.getComponent(TeamScoreBoard)
            .show();
        this.addComponents(this.context.views.out);
    }

    private getOutPlayer() {
        const players = this.context.players.getAll();
        if (players.length === 0) return;

        const max = Math.max(...players.map((p) => p.votes));
        if (max === 0) return null;

        const maxPlayers = players.filter((p) => p.votes === max);
        return maxPlayers.length === 1 ? maxPlayers[0] : undefined;
    }

    next() {
        this.popState();
    }
}
